'use client';

import React from 'react';
import { AccountModel, EventModel } from '../lib/api';

interface Message {
  id: string;
  actor: string;
  owner: string;
  created_at: string;
  content: string;
  type: string;
}

interface Props {
  owner: string;
  friends: string[];
  accountMap: Record<string, AccountModel>;
  activeFriend: string;
  onSelectFriend: (friend: string) => void;
  events: EventModel[] | undefined;
  loading: boolean;
}

const ALL_CHATS = '__ALL__';

function parseMentions(raw: string | undefined): string[] {
  if (!raw) return [];
  return raw
    .split(/\s+/)
    .map(token => token.replace(/^@/, '').trim())
    .filter(Boolean);
}

function normalizeMessages(
  events: EventModel[] | undefined,
  owner: string,
  friend: string,
  knownFriends: string[]
): Message[] {
  if (!events) return [];
  const friendSet = new Set(knownFriends);
  const byId = new Map<string, EventModel>();
  events.forEach(ev => byId.set(ev.id, ev));

  const filtered = events.filter(event => {
    const actor = event.actor;
    const mentions = parseMentions(event.headers['mentions']);

    if (friend === ALL_CHATS) {
      return actor === owner || friendSet.has(actor) || mentions.includes(owner);
    }

    if (actor === friend) {
      return true;
    }

    if (actor === owner && mentions.includes(friend)) {
      return true;
    }

    if (actor === friend && mentions.includes(owner)) {
      return true;
    }

    const inReplyTo = event.headers['in_reply_to'];
    if (inReplyTo) {
      const target = byId.get(inReplyTo);
      if (target) {
        if (actor === owner && target.actor === friend) return true;
        if (actor === friend && target.actor === owner) return true;
      }
    }

    return false;
  });

  return filtered
    .map(ev => ({
      id: ev.id,
      actor: ev.actor,
      owner: ev.owner,
      created_at: ev.created_at,
      content: ev.content.trim() || ev.headers['summary'] || ev.type,
      type: ev.type
    }))
    .sort((a, b) => new Date(a.created_at).getTime() - new Date(b.created_at).getTime());
}

export function ConversationPanel({ owner, friends, accountMap, activeFriend, onSelectFriend, events, loading }: Props) {
  const friendList = React.useMemo(() => [ALL_CHATS, ...friends], [friends]);

  React.useEffect(() => {
    if (!friendList.includes(activeFriend)) {
      onSelectFriend(friendList.length > 0 ? friendList[0] : ALL_CHATS);
    }
  }, [activeFriend, friendList, onSelectFriend]);

  const messages = React.useMemo(
    () => normalizeMessages(events, owner, activeFriend, friends),
    [events, owner, activeFriend, friends]
  );

  const friendAccount = activeFriend === ALL_CHATS ? null : accountMap[activeFriend];
  const friendLabel = (id: string) => {
    if (id === ALL_CHATS) return 'All chats';
    return accountMap[id]?.display_name ?? id;
  };

  const activeLabel = activeFriend === ALL_CHATS ? 'All conversations' : friendLabel(activeFriend);
  const activeType = activeFriend === ALL_CHATS ? `${friends.length} friends across spaces` : (friendAccount?.type ?? 'agent');
  const createdAt = friendAccount?.created_at;

  return (
    <section className="panel conversation">
      <header className="panel-header">
        <div>
          <h2>Chats</h2>
          <span className="muted">Conversations for {owner}</span>
        </div>
      </header>
      <div className="profile-card">
        <div className="avatar-large">
          {activeFriend === ALL_CHATS ? '∞' : (friendAccount?.display_name ?? activeFriend).slice(0, 1).toUpperCase()}
        </div>
        <div className="profile-details">
          <strong>{activeLabel}</strong>
          <span className="muted">{activeType}</span>
          {createdAt && <small className="muted">since {new Date(createdAt).toLocaleDateString()}</small>}
        </div>
      </div>
      <div className="friend-list">
        {friendList.map(friend => (
          <button
            key={friend}
            className={`friend-pill${friend === activeFriend ? ' active' : ''}`}
            onClick={() => onSelectFriend(friend)}
          >
            {friend === ALL_CHATS ? 'All chats' : accountMap[friend]?.display_name ?? friend}
          </button>
        ))}
        {friends.length === 0 && <span className="muted">No friends yet — start a post!</span>}
      </div>
      <div className="panel-body conversation-body">
        {loading && <p className="muted">Loading chat…</p>}
        {!loading && messages.length === 0 && <p className="muted">No messages with {activeLabel} yet.</p>}
        {messages.map(msg => {
          const isOwner = msg.actor === owner;
          const actorLabel = accountMap[msg.actor]?.display_name ?? msg.actor;
          return (
            <article key={msg.id} className={`chat-bubble${isOwner ? ' mine' : ''}`}>
              <header>
                <strong>{actorLabel}</strong>
                <time>{new Date(msg.created_at).toLocaleString()}</time>
              </header>
              <p>{msg.content || '(no content)'}</p>
              <footer className="muted">{msg.type}</footer>
            </article>
          );
        })}
      </div>
    </section>
  );
}
